import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO, USER_NAME, INTERFACE_PREFIX, LING_YANG_ROLE_TYPE } from "@/store/mutation-types"
import { apiBaseUrl } from "@/utils/request";
import { postAction } from '@/api/manage'
import axios from 'axios'
import store from '../store'
import * as dd from "dingtalk-jsapi";
import { getRoute } from '@/api/login'
export function onWindowLoad(frame, timeout, onSuccess, onError) {
  if (!frame) {
    return onError('不是 frame 对象')
  }
  // 查看是否跨域
  try {
    frame.document
  } catch (e) {
    return onError(e)
  }
  if (!frame.document) {
    return onError('不是 frame 对象')
  }
  if (frame.document.readyState === 'complete') {
    return onSuccess(frame)
  } else {
    var isRes = false
    function onLoadWrap(oldListener) {
      return function () {
        oldListener && oldListener()
        if (frame.document.readyState !== 'interactive') {
          var callback = frame.document.readyState === 'complete' ? onSuccess : onError
          callback && callback()
        }
        isRes = true
      }
    }
    // 绑定句柄
    frame.document.onreadystatechange = onLoadWrap(frame.document.onreadystatechange)
    frame.document.onload = onLoadWrap(frame.document.onload)
    // 处理超时的场景
    if (timeout) {
      setTimeout(function () {
        if (!isRes) {
          isRes = true
          onError('timeout')
        }
      }, timeout)
    }
    // 处理绑定的句柄被 改写的问题 用轮询 监听 frame状态改变
    ; (function poll() {
      if (frame.readyState == 'complete') {
        isRes = true
        onSuccess()
      } else {
        if (!isRes) {
          setTimeout(poll, 4)
        }
      }
    })()
  }
}
export function login() {
  return new Promise((resolve, reject) => {
    //延时是为了等js包加载完成在触发调用方法
    onWindowLoad(
      window,
      60000,
      () => {
        let domainURL = window.location.href
        let domainParams = myParams(domainURL)
        if (domainParams.appToken) {
          workFun(resolve, reject, domainParams.appToken)
        } else {
          let isDingDing = dd.env.platform == 'notInDingTalk' ? false : true;
          if (isDingDing) {
            sessionStorage.setItem('currentEnvironment', 'dingding')
            dingFun(domainParams.corpId, resolve, reject)
          } else if (domainParams.token) {
            sessionStorage.setItem('currentEnvironment', 'browser')
            lingYangFun(domainParams, resolve, reject)
            return
          } else {
            sessionStorage.setItem('currentEnvironment', 'browser')
            pubFail(reject, 'browser')
          }
        }
      },
      () => {
        pubFail(reject, 'allFail')
      }
    );
  });
}
function workFun(resolve, reject, appToken) {
  sessionStorage.setItem('currentEnvironment', 'iwork')
  let firstObj = {
    appToken: appToken,
  };
  axios({
    method: "post",
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    url: apiBaseUrl + "/jksaas-mgt/mgt/iwork/login",
    data: firstObj,
  })
    .then((response) => {
      if (response.data.code == 200) {
        loginSuccess(response.data.result.token)
        let initData = response.data.result.initData
        axiosSuccess('iworkSuccess_requestSuccess', response, resolve, initData)
      }
    })
    .catch((e) => {
      pubFail(reject, 'iworkSuccess_requestFirstFail')
    });
}
function dingFun(corpId, resolve, reject) {
  dd.ready(function () {
    dd.runtime.permission.requestAuthCode({
      corpId: corpId,
      onSuccess: function (result) {
        console.log('这里是钉钉环境且成功', result);
        sessionStorage.setItem('currentEnvironment', 'dingding')
        let firstObj = {
          code: result.code,
          corpId,
        };
        axios({
          method: "post",
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          url: apiBaseUrl + "/jksaas-mgt/mgt/sys/thirdlogin/dingDingLogin",
          data: firstObj,
        }).then(response => {
          if (response.data.code == '200') {
            loginSuccess(response.data.result.token)
            axiosSuccess('ddSuccess_requestSuccess', response, resolve)
          }
        }).catch(error => {
          pubFail(reject, 'ddSuccess_requestFirst_Fail')
        })

      },
      onFail: function (err) {
        console.log('这里是钉钉环境且失败', err);
        pubFail(reject, 'ddFail')
      },
    });
  });
}
function lingYangFun(domainParams, resolve, reject) {
  Vue.ls.set(LING_YANG_ROLE_TYPE, domainParams.type)
  postAction(`/antelope/login`,{token: domainParams.token, type: domainParams.type}).then(res => {
      if (res.code == '200') {
        let initData = res.result.initData
        let response = {data: res}
        loginSuccess(response.data.result.token)
        axiosSuccess('lySuccess_requestSuccess', response, resolve, initData)
      } else {
        Vue.prototype.$Jnotification.error({
          message: '系统提示',
          description: res.message,
          duration: 4
        })
        pubFail(reject, 'browser')
      }
    })
    .catch(error => {
      // Vue.prototype.$Jnotification.error({
      //   message: '系统提示',
      //   description: error,
      //   duration: 4
      // })
      pubFail(reject, 'browser')
    })
}
function myParams(domainURL) {
  let obj = {};
  if (domainURL.indexOf('?') != -1) {
    let newStr = domainURL.slice(domainURL.indexOf('?') + 1); //从?开始截取到最后[不含问号]
    // 将#号转换成格式相同的,并进行分割为数组
    let ary = newStr.replace(/#/g, '&HASH=').split('&');
    for (let i = 0; i < ary.length; i++) {
      // 将ary中的小数组用等号进行拆分
      let tempAry = ary[i].split('=');
      // 判定拆分后的数组第二个字符串是否为数字(当前规则不考虑=0的情况)
      if (!Number(tempAry[1])) { // 为非数字
        obj[tempAry[0]] = tempAry[1];
      } else {
        obj[tempAry[0]] = Number(tempAry[1]); // 是数字则直接转成数字显示
      }
    }
  }
  return obj;
}
function axiosSuccess(axiosType, response, resolve, initData) {
  let currentToken = response.data.result.token
  let userInfo = response.data.result.userInfo
  Vue.ls.set(ACCESS_TOKEN, currentToken, 7 * 24 * 60 * 60 * 1000);
  Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
  Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
  store.commit('SET_TOKEN', currentToken)
  store.commit('SET_INFO', userInfo)
  store.commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname })
  store.commit('SET_AVATAR', userInfo.avatar)
  if (axiosType == 'lySuccess_requestSuccess' || axiosType == 'iworkSuccess_requestSuccess' && JSON.stringify(initData) != '{}') {
    postAction('/antelope/initAfterLogin',initData)
  }
  resolve();
}
function pubFail(reject, failType) {
  reject({
    rejectType: failType
  });
}

// url参数切割
function Urlquery(type) {
  let url = location.href.substring(location.href.indexOf('?')) || ''
  if (!url) {
    return ''
  }
  let query = {}
  url = url.substring(1)
  url = url.split('&')
  for (let item of url) {
    item = item.split('=')
    query[item[0]] = item[1]
  }
  return query[type]
}

function loginSuccess(token) {
  getRoute(token, `/jksaas-mgt/mgt/newSys/permission/getRoute`).then(res => {
    Vue.ls.set(INTERFACE_PREFIX, res.data.result, 7 * 24 * 60 * 60 * 1000)
    store.commit('SET_INTERFACE_PREFIX', res.data.result)
  })
}